import React, {Component} from 'react';
import {
	ActivityIndicator,
	Alert,
	Dimensions,
	FlatList,
	Image,
	RefreshControl,
	StyleSheet,
	Text,
	TextInput,
	TouchableOpacity,
	View,
} from 'react-native';
import SelfadaptModal from 'react-native-selfadapt-modal';
import axiosInstance from './utils/request';
import BackImage from './component/BackImage';
import ScrollableTabView, {DefaultTabBar} from 'react-native-scrollable-tab-view';
import CostHisScene from './pay/CostHisScene';

import getStyles from '../style/styles';
import MeterBook from './meterbook/MeterBook';

let rows=20;//
let totalPage=0;//总的页数
let itemNo=0;//item的个数

const menuItem = [
    {flag:'last',name:'接上次抄表'},
    {flag:'first',name:'从第一户抄表'},
	{flag:'order',name:'按顺序抄表'},
];

//屏幕信息
var dimensions = require('Dimensions');
//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;

let styles={};

export default class MeterBooksScene extends Component {

	static navigationOptions =({ navigation,route }) => {

		console.log(navigation);

		return {

			title:route.params.title,
			headerStyle: {
				backgroundColor: 'rgba(0, 191 ,255, 0.5)',
			},
			headerBackImage:<BackImage/>, //使用组件
			headerTintColor: '#fff',
			headerTitleStyle: {
				fontWeight: 'bold',
			},
			headerRight:(
				<TouchableOpacity
					activeOpacity={0.5}
					onPress={navigation.getParam('navigatePress')}>
					{	//精简版注释部分
						//navigation.getParam('tabIndex')==0||navigation.getParam('tabIndex')==1 ?
						//<Image style={{height: 40, width: 40,marginRight:10}} source={require('../img/qrCode.png')}/>
						//:<Image style={{height: 40, width: 50,marginRight:10}} source={require('../img/search.png')}/>

					}
				</TouchableOpacity>
			)
		}
	};

	navigatePress = () => {
		let tabIndex=this.state.tabIndex;
		const {navigate} = this.props.navigation;
		if(tabIndex==0){
			navigate('ScannerScreen', {page:'CustInfoEditScene'});
		}else if(tabIndex==1){
			navigate('ScannerScreen', {page:'Entry'});
		}else if(tabIndex==2){
			 this.costHisRef.setModalVisible(true);
		}
    }

	setHeader(tabIndex){
		this.setState(
		{
			tabIndex:tabIndex,
		},()=>{
			if(tabIndex==0){
				this.props.navigation.setParams({ title: '用户管理',tabIndex:tabIndex});
			}else if(tabIndex==1){
				this.props.navigation.setParams({ title: '抄表收费',tabIndex:tabIndex});
			}else if(tabIndex==2){
				this.props.navigation.setParams({ title: '用户退费',tabIndex:tabIndex});
			}
		})
	}

    constructor(props){
		super(props);
		this.state = {
			page:1,
            isLoading: true,
            //网络请求状态
            error: false,
            errorInfo: "",
			title:"抄表收费",
			tabIndex:1,
            dataArray: [],
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing:false,//下拉控制
			modalVisible: false,//模态场景是否可见
	 	};
	}

	//组件挂载完成后执行的方法
    componentDidMount(){
		this.setNav()
        //组件挂载后开始下载数据
        this.fetchData('');
    }

    setNav(){
		this.props.navigation.setOptions({
			title:'抄表收费',
		})
		this.props.navigation.setParams({ title: this.state.title,tabIndex:this.state.tabIndex});
		this.props.navigation.setParams({ navigatePress: this.navigatePress });
	}

	/*
		因为服务端modified字段代表的是时间戳，所以Max(anchor)表示客户端最近一次同步的时间，如果存在服务端modified > Max(anchor),
		说明服务端需要向客户端同步数据。
	*/
	fetchData(bookName){
		let URL= global.server.url+'/meterBooks/selectListPage';
		if(bookName){
			page=1;
		}else{
			page=this.state.page;
		}
		axiosInstance.post(URL,
			{
				bookName:bookName,
				pageVO:{
					page:page,
					rows:rows
				}
			}
		)
        .then(res => {
			let datas = [];
			let list=res.list;
			let count=list.records.length;
			totalPage=list.pages;
			datas = datas.concat(list.records);
            let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
            let i = itemNo;
            datas.map(function (item) {
            	dataBlob.push({
                	key: i,
					bookId:item.id,
                    bookNo: item.bookNo,
                    bookName: item.bookName,
					custNumber:item.custNumber
                })
                i++;
            });
            itemNo = i;
            let foot = 0;
            if(this.state.page>=totalPage){
                foot = 1;//listView底部显示没有更多数据了
            }

            this.setState({
                //复制数据源
            	//  dataArray:this.state.dataArray.concat( responseData.results),
                dataArray:this.state.dataArray.concat(dataBlob),
                isLoading: false,
                showFoot:foot,
                isRefreshing:false,
				count:count
            });
            datas = null;//重置为空
            dataBlob = null;
        })
        .catch(error => {
			console.log('error:',error);
        	this.setState({
				error: true,
                errorInfo: error.errorInfo
			});
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	shouldComponentUpdate() {
        return true
    }

    handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchData()
    }

	//加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    _keyExtractor = (item, index) => index;

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

	searchData(){
		let bookName=this.state.bookName;
		this.setState({
            dataArray:[]
        });
		this.fetchData(bookName);
    }

 	_onChangeText(text) {
		if (text) {
			this.setState({
				bookName: text,
				dataArray:[]
			})  //实时变化值
			clearTimeout(this.settimeId);       //如搜索的内容变化在1秒之中，可以清除变化前的fetch请求，继而减少fetch请求。但不能中断fetch请求
			this.settimeId = setTimeout(() => {
				this.fetchData(text);
			}, 1000);                                      //让每次要进行fetch请求时先延迟1秒在进行
		  	console.log("sheng chen id:" + this.settimeId);
		} else {
			this.setState({bookName: '' })
		}
	}

	doSelect = (value,item) => {
		if(value.flag=='order'){//如果是按顺序抄表，则跳转到CostMasterScene
			this.props.navigation.navigate('CostMasterScene', {bookId:item.bookId,bookName:item.bookName});
		}else{
			this.props.navigation.navigate('Entry', {bookId:item.bookId,flag:value.flag});
		}
	}

	renderData() {
		styles=getStyles();
        return (
			<ScrollableTabView
				style={style.container}
				tabBarUnderlineStyle={{backgroundColor:'#000000', height:1}}
				initialPage={this.state.tabIndex}
				renderTabBar={()=><DefaultTabBar backgroundColor='rgba(255, 255 ,255, 0.5)' />}
				tabBarPosition='bottom'
				onChangeTab={
                    (obj) => {
						this.setHeader(obj.i);
                    }
                }
		    >
			{/*精简版将‘退费’放到最前面，是为了打开是默认显示‘抄表’标签，非精简版应该将退费标签放置到最后*/}
			<View style={style.container} tabLabel ="退费">
				<CostHisScene ref={this.costHisRef} />
			</View>

			{/*精简版注释部分
			<View style={style.container} tabLabel ="用户">
				<CustInfoScene navigation={this.props.navigation}/>
			</View>
			*/}
			<MeterBook tabLabel={'抄表'} navigation={this.props.navigation}/>
		</ScrollableTabView>
        );
    }

    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

    _separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
    	if (this.state.page>1){
            this.fetchData();
        }
    }
}

var width = WIN_WIDTH/2;
const style = StyleSheet.create({
	container: {
        flex: 1,
    },
	oneBtn: {
        padding: 5,
        borderRadius: 5,
    },
	oneBox: {
    	flexDirection: 'row',
        alignItems: 'center',
    },
});
